package fun.xinnix.websocket.service;

import com.alibaba.fastjson.JSON;
import fun.xinnix.websocket.domain.Constant;
import fun.xinnix.websocket.domain.MessageType;
import fun.xinnix.websocket.domain.SendMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);

    private final AttributeKey<String> key = AttributeKey.valueOf(Constant.WEBSOCKET_ATTRIBUTEKEY_USER);

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketHandler.applicationContext = applicationContext;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        logger.info(ctx.channel().remoteAddress() + "收到信息!" + msg.text());
        try {
            SendMessage send_message = JSON.parseObject(msg.text(), SendMessage.class);
            handleMessage(ctx.channel(), send_message);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        String userIdByChannel = ChannelHandlerPool.getUserIdByChannel(ctx.channel());
        ChannelHandlerPool.channelGroup.remove(ctx.channel());
        logger.info("{}与客户端断开连接！当前连接数：{}, ", userIdByChannel, ChannelHandlerPool.channelGroup.size());
    }

    /**
     * 每个传入的消息都会调用
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 首次连接是FullHttpRequest，处理参数
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();

            // 转换连接时附带的参数
            ConcurrentMap<String, String> paramMap = getUrlParams(uri);
            if (paramMap.size() < 2) {
                logger.info("参数不对");
                ctx.close();
                return;
            }
            if (!paramMap.containsKey("salesmanId")) {
                logger.info("业务员id为空");
                ctx.close();
                return;
            }
            if (!paramMap.containsKey("token")) {
                logger.info("token为空");
                ctx.close();
                return;
            }

            String userKey = paramMap.get("salesmanId") + "-" + paramMap.get("token");

            // 添加到连接池
            addChannelGroup(userKey, ctx.channel());
            logger.info("与客户端建立连接！当前连接数：" + ChannelHandlerPool.channelGroup.size());
            // 如果url包含参数，需要处理
            if (uri.contains("?")) {
                String newUri = uri.substring(0, uri.indexOf("?"));
                request.setUri(newUri);
            }
        }
        super.channelRead(ctx, msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    private void handleMessage(Channel channel, SendMessage msg) {
        if (msg != null) {
            // 心跳数据就处理
            if (msg.getMessageType().compareTo(MessageType.HEARTBEAT) == 0) {
                String corrUserId = ChannelHandlerPool.getUserIdByChannel(channel);
                WebsocketUtils.getInstance().SendHeartbeat(channel, corrUserId);
                msg.setFromUserId(corrUserId);
                logger.info("收到心跳数据" + JSON.toJSONString(msg));
            } else {
                WebsocketUtils.getInstance().sendMessageMsg(msg);
            }
        }
    }

    /**
     * 用户上线
     */
    private void addChannelGroup(String userKey, Channel channel) {
        channel.attr(key).set(userKey);
        ChannelHandlerPool.channelGroup.add(channel);

    }

    /**
     * 获取url的参数
     */
    private static ConcurrentMap<String, String> getUrlParams(String url) {
        ConcurrentMap<String, String> map = new ConcurrentHashMap<>();
        url = url.replace("?", ";");
        if (!url.contains(";")) {
            return map;
        }
        if (url.split(";").length > 0) {
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr) {
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key, value);
            }
        }
        return map;
    }

}
